import axios from "axios";
import {SignJWT} from "jose";
const apiKey = "69cc20b98762eddd9775bbf44dbbda98.xgbuAiJTCPzS2GsJ"
async function getToken() {
    let [id,secret] = apiKey.split(".")
    let header = {"alg":"HS256","sign_type":"SIGN"}
    let payload = {
        "api_key":id,
        "timestamp":Math.floor(Date.now()/1000),
        "exp":Math.floor(Date.now()/1000)+3600
    }
    let secretBin=new TextEncoder().encode(secret)
    let token = await new SignJWT(payload)
        .setProtectedHeader(header)
        .sign(secretBin)
    return token
}
export default async function chatglmapi(history:Array<{role:string,content:string}>,
                                   callback:(event:{id:string,event:string,data:string},history:Array<{role:string,content:string}>)=>void,debug=true) {
    if(!debug){
        let response = await fetch('/chatglm',{
            method:"POST",
            headers:{
                'Accept': 'text/event-stream',
                "Authorization":await getToken(),
                "Content-Type":"application/json",
            },
            body:JSON.stringify({
                "prompt":history,
                "temperature":0.75,
                "incremental":true
            })
        })
        if(response.status==200 && response.body){
            const reader = response.body.getReader();
            let result = "";
            let buffer = "";
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                let result = new TextDecoder().decode(value)
                buffer += result;
                let lines = result.split('\n');
                let event = {
                    id:"",
                    event:"",
                    data:""
                }
                for(let line of lines){
                    let keyAndValue = line.split(':');
                    if(keyAndValue[0].trim() === 'id'){
                        event.id = keyAndValue[1]
                    }else if(keyAndValue[0].trim() === 'event'){
                        event.event = keyAndValue[1]
                    }else if(keyAndValue[0].trim() === 'data'){
                        event.data = keyAndValue[1]
                    }
                }
                callback(event,history);
            }
        }
    }else{
        callback({id:"debug",event:"add",data:"冰雪世界中，艺术家颜冬完成冰雕作品，抬头望见高速飞行的低温艺术家，其尾迹在蓝天上留下巨大痕迹。一个巨大的灰白色"},history)
        callback({id:"debug",event:"finish",data:""},history)
    }


}
